# -*- coding: utf-8 -*-
"""
@Time   :  "2024/8/7 22:37"
@Author :  Dilee
"""
import os

from flask import Flask
from flask_migrate import Migrate

from config import Config
from internal.exception import CustomException
from internal.router import Router
from pkg.response import json, Response, HttpCode
from pkg.sqlalchemy import SQLAlchemy

config = Config()


class Http(Flask):
    """http服务"""

    def __init__(self, *args, conf: Config, migrate: Migrate, db: SQLAlchemy, router: Router, **kwargs):
        super().__init__(*args, **kwargs)

        # 初始化应用配置
        self.config.from_object(conf)

        # 处理异常
        self.register_error_handler(Exception, self._register_error_handler)

        # 初始flask扩展数据库初始化
        db.init_app(self)
        migrate.init_app(self, db, directory="internal/migration")
        # 注册路由
        router.register_router(self)

    # 处理异常
    def _register_error_handler(self, error: Exception):
        if isinstance(error, CustomException):
            return json(Response(
                code=error.code,
                message=error.message,
                data=error.data if error.data is not None else {}
            ))
        if os.getenv("FLASK_DEBUG") == "1" and os.getenv("FLASK_ENV") == "development":
            raise error
        else:
            return json(Response(
                code=HttpCode.FAIL,
                message=str(error),
                data={}
            ))
